import 'dart:convert' as convert;

import 'package:dio/dio.dart';
import 'package:duo_zui/model/model.dart';
import 'package:flutter/material.dart';
import 'package:duo_zui/constant/constant.dart';
import 'package:duo_zui/widget/heart_img_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:duo_zui/constant/cache_key.dart';
import 'package:duo_zui/main.dart';

import '../router.dart';
typedef VoidCallback = void Function();

///个人中心
class PersonCenterPage extends StatefulWidget {

  bool islogin;
  User myUser;

  PersonCenterPage({Key key,
      this.islogin = false,
      this.myUser,})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _PersonCenterPageStage();
}

class _PersonCenterPageStage extends State<PersonCenterPage>{
  String token = '';
  bool islogin = false;
  User myUser = new User();
  String name;

  @override
  Widget build(BuildContext context) {
    print('build PersonCenterPage');
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
          child: Padding(
            padding: EdgeInsets.only(top: 10.0),
            child: CustomScrollView(
              physics: const BouncingScrollPhysics(),
              shrinkWrap: false,
              slivers: <Widget>[
                SliverAppBar(
                  backgroundColor: Colors.transparent,
                  title: Text("我的"),
                  automaticallyImplyLeading:false,
                  leading: InkWell(
                    child: new Padding(
                        padding: const EdgeInsets.all(12.0),
                        child: new Icon(
                          Icons.arrow_back,
                          size: 26.0,
                          color: Colors.grey[700],
                        )),
                    onTap: () {
                      //Navigator.pop(context);
                      MyRouter.pushNoParams(context, MyRouter.homePage);
                    },
                  ),
                  //expandedHeight: 200.0,
                ),
                _divider(),
                SliverToBoxAdapter(
                  child: GestureDetector(
                    onTap: (){
                      _rourLogin(MyRouter.myhomePage, {'user': myUser});
                    },
                    child: Container(
                        height: 100.0,
                        alignment: Alignment.centerLeft,
                        child: LoginBar()),
                  ),
                ),
                _divider(),
                _personItem('ic_notify.png', '消息中心'),
                _small_divider(),
                _personItem('ic_me_follows.png', '我的关注'),
                _small_divider(),
                _personItem('zan.png', '我赞过的'),
                _small_divider(),
                _personItem('ic_me_photo_album.png', '阅读过的文章'),
                _small_divider(),
                _personItem('ic_me_doulist.png', '收藏'),
                _divider(),
                _personItem('ic_me_wallet.png', '意见反馈',onTab: (){

                }),
                _small_divider(),
                _personItem('seting.png', '设置', onTab: (){
                  _rourLogin(MyRouter.settingPage, {'user': myUser});
                }),
              ],
            ),
          )),
    );
  }

  _rightArrow() {
    return Icon(
      Icons.chevron_right,
      color: const Color.fromARGB(255, 204, 204, 204),
    );
  }

  SliverToBoxAdapter _small_divider() {
    return SliverToBoxAdapter(
      child: Container(
        height: 1.0,
        color: const Color.fromARGB(255, 247, 247, 247),
      ),
    );
  }

  SliverToBoxAdapter _divider() {
    return SliverToBoxAdapter(
      child: Container(
        height: 10.0,
        color: const Color.fromARGB(255, 247, 247, 247),
      ),
    );
  }

  SliverToBoxAdapter _personItem(String imgAsset, String title,
      {VoidCallback onTab}) {
    return SliverToBoxAdapter(
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        child: Row(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.all(10.0),
              child: Image.asset(
                Constant.ASSETS_IMG + imgAsset,
                width: 25.0,
                height: 25.0,
              ),
            ),
            Expanded(
              child: Text(
                title,
                style: TextStyle(fontSize: 15.0),
              ),
            ),
            _rightArrow()
          ],
        ),
        onTap: onTab,
      ),
    );
  }



  @override
  void initState() {
    super.initState();
    _getData();
  }

  _getData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      islogin = widget.islogin ?? false;
      myUser = widget.myUser;
      if(!islogin){
        if(prefs.getBool(CacheKey.USER_IS_LOGIN)??false){
          islogin = prefs.getBool(CacheKey.USER_IS_LOGIN);
          Map<String,dynamic> map = convert.jsonDecode(prefs.getString(CacheKey.User_CACHE)??'');
          myUser = User.fromJson(map);
        }
      }
    });
  }

  _rourLogin(key,params) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if(prefs.getBool(CacheKey.USER_IS_LOGIN)?? false){
      MyRouter.push(context, key, params);
    }else{
      MyRouter.push(context, MyRouter.loginPage, {'url': MyRouter.personDetailPage});
    }
  }

  Widget LoginBar(){
    Widget widget;
    if(islogin){
      widget = Row(
        children: <Widget>[
          Padding(
              padding: EdgeInsets.only(
                  left: 15.0, top: 20.0, bottom: 20.0, right: 10.0),
              child: CircleAvatar(
                  radius: 40,
                  backgroundImage: NetworkImage(
                      myUser.photo
                  ),
              )
          ),
          Expanded(
            child: Text(
              myUser.nickname,
              style: TextStyle(fontSize: 17.0),
            ),
          ),
          _rightArrow()
        ],
      );
    }else{
      widget = Row(
        children: <Widget>[
          Padding(
              padding: EdgeInsets.only(
                  left: 15.0, top: 20.0, bottom: 20.0, right: 10.0),
              child: Icon(
                Icons.account_circle,
                color: Colors.black38,
                size: 40.0,
              )
          ),
          Expanded(
            child: Text(
              '登录/注册',
              style: TextStyle(fontSize: 17.0),
            ),
          ),
          _rightArrow()
        ],
      );
    }
    return widget;
  }
}

///影视、图书、音乐 TAB
class _VideoBookMusicBookWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _VideoBookMusicBookWidgetState();
}

class _VideoBookMusicBookWidgetState extends State<_VideoBookMusicBookWidget>
    with SingleTickerProviderStateMixin {
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: tabTxt.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 130.0,
      child: DefaultTabController(
          length: tabTxt.length,
          child: Column(
            children: <Widget>[
              Align(
                child: _TabBarWidget(),
                alignment: Alignment.centerLeft,
              ),
              _tabView()
            ],
          )),
    );
  }

  Widget _tabView() {
    return Expanded(
      child: TabBarView(
        children: [
          _tabBarItem('bg_videos_stack_default.png'),
          _tabBarItem('bg_books_stack_default.png'),
          _tabBarItem('bg_music_stack_default.png'),
        ],
        controller: _tabController,
      ),
    );
  }

  Widget getTabViewItem(String img, String txt) {
    return Column(
      children: <Widget>[
        Expanded(
          child: Padding(
            padding: EdgeInsets.only(top: 15.0, bottom: 7.0),
            child: Image.asset(
              Constant.ASSETS_IMG + img,
              fit: BoxFit.contain,
            ),
          ),
        ),
        Text(txt)
      ],
    );
  }

  _tabBarItem(String img) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: <Widget>[
        getTabViewItem(img, '想看'),
        getTabViewItem(img, '在看'),
        getTabViewItem(img, '看过'),
      ],
    );
  }
}

///
///
class _TabBarWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _TabBarWidgetState();
}

TabController _tabController;

class _TabBarWidgetState extends State<_TabBarWidget> {
  Color selectColor, unselectedColor;
  TextStyle selectStyle, unselectedStyle;
  List<Widget> tabWidgets;

  @override
  void initState() {
    super.initState();
    selectColor = Colors.black;
    unselectedColor = Color.fromARGB(255, 117, 117, 117);
    selectStyle = TextStyle(fontSize: 18, color: selectColor);
    unselectedStyle = TextStyle(fontSize: 18, color: selectColor);
    tabWidgets = tabTxt
        .map((item) =>
        Text(
          item,
          style: TextStyle(fontSize: 15),
        ))
        .toList();
  }

  @override
  void dispose() {
    super.dispose();
    if (_tabController != null) {
      _tabController.dispose();
    }
  }

  @override
  Widget build(BuildContext context) {
    return TabBar(
      tabs: tabWidgets,
      isScrollable: true,
      indicatorColor: selectColor,
      labelColor: selectColor,
      labelStyle: selectStyle,
      unselectedLabelColor: unselectedColor,
      unselectedLabelStyle: unselectedStyle,
      indicatorSize: TabBarIndicatorSize.label,
      controller: _tabController,
    );
  }
}

final List<String> tabTxt = ['影视', '图书', '音乐'];


